package com.pl.DateFormat;

/**
 * @version 1.0
 * @Author 小胤
 * @Date 2024/4/23 11:03
 * @注释
 */

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义一个  easyexcel的时间格式转换器
 */
public class DateConverter implements Converter<Date> {


    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    @Override
    public Class<Date> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override  // 将excel 中的日志字符串 转化为 java.utils.Date
    public Date convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        // cellData 就是包裹时间的单元格
        String dateString = cellData.getStringValue();
        if (dateString == null || dateString.isEmpty()) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            // 解析失败，返回 null 或者抛出异常，视情况而定
            e.printStackTrace();
            return null;
        }
    }

    @Override // 将java的Date 转化为符合格式的 字符串
    public CellData convertToExcelData(Date value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (value == null) {
            return new CellData<>("");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
        return new CellData<>(sdf.format(value));
    }


}

